import React, { Component, useEffect } from 'react'
import { Layout } from 'antd'
import HeaderComponent from './header'
import SideBarComponent from './side'
import SSHComponent from './pages/ssh'
import ShareComponent from './pages/share'
import HttpPage from './pages/http'

// map路由页面
interface MapComponent {
  [key: string]: React.FC
}

const MapPage: MapComponent = {
  '1': SSHComponent,
  '2': ShareComponent,
  '3': HttpPage,
  '4': ShareComponent,
}

// function renderContentComponent(key: string) {
//   const Component = MapPage[key]
//   if (Component) {
//     return <Component />
//   }
// }

const AppLayout: React.FC = () => {
  // 监听子组件的值变化，并更新父组件的值
  const [currentMenu, setCurrentMenu] = React.useState('1')
  // 记录所有已加载的组件（避免重复渲染）
  const [loadedComponents, setLoadedComponents] = React.useState<Set<string>>(
    new Set([currentMenu]),
  )

  const handleChildChange = (value: string) => {
    if (value !== '') {
      setCurrentMenu(value)
    }
  }

  // 当菜单切换时，标记组件为已加载
  useEffect(() => {
    setLoadedComponents((prev) => new Set([...prev, currentMenu]))
  }, [currentMenu])

  useEffect(() => {
    return () => {
      window.addEventListener('unhandledrejection', (event) => {
        if (event.reason && event.reason.name === 'Canceled') {
          event.preventDefault()
          // custom logging
        }
      })
    }
  })

  return (
    <Layout style={{ height: '100vh' }}>
      {/* 顶部导航栏 */}
      {HeaderComponent()}

      <Layout>
        {/* 侧边栏 */}
        <SideBarComponent onChange={handleChildChange} />

        {/* 主内容区域 */}
        {/* {currentMenu && renderContentComponent(currentMenu)} */}
        {Array.from(loadedComponents).map((key) => {
          const Component = MapPage[key]
          return (
            <div
              key={key}
              style={{
                width: 'calc(100% - 200px)',
                display: currentMenu === key ? 'block' : 'none',
              }}
            >
              <Component />
            </div>
          )
        })}
      </Layout>
    </Layout>
  )
}

export default AppLayout
